# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json
from common.helper import Helper


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "健康金福个人中端医疗保险（2017款）"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            # 年龄段
            "year": [str(i) for i in range(0, 66)],
            # 有无社保
            "socialSec": ["Y", "N"],
            # 一般医疗保险金
            "generalMedical": ["1000000"],
            # 恶性肿瘤保险金
            "cancerMedical": ["1000000"],
            # 赔付比例
            "payRate": ["100%"],
            # 年度免赔额
            "deductible": ["10000"]
        }
        for v in product(plan["year"], plan["socialSec"], plan["generalMedical"], plan["cancerMedical"],
                         plan["payRate"], plan["deductible"]):
            data = Helper.formatProductInfo(plan, v)
            self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(**data))
            self.mysql._conn.commit()
            print(domain[self.name]["insert_sql"].format(**data))

    # 执行爬虫
    def requestJson(self,dt=None):

        data = {"head": {"batchNo": "TBFWBDSSBDSS20200402090347422363", "branchCode": "TBFWBDSS",
                         "sendDate": "2020-04-02 09:03:47"}, "body": {"insured": [{"sex": 0, "birthday": "{0}-01-01".format( str(2020-int(dt["year"])))}],
                                                                      "securityList": [
                                                                          {"a": "一般医疗保险金#100万", "b": "恶性肿瘤医疗保险金#100万",
                                                                           "c": "赔付比例#100%", "d": "年度免赔额#1万（恶性肿瘤0免赔）",
                                                                           "e": "累计赔付限额#200万"}], "wrapCode": "ZZJ367",
                                                                      "cvaliDate": "2020-04-03", "mult": 1 if dt["socialSec"] == "N" else "2"}}
        payload = json.dumps( data )
        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)
        if r.status_code == 200 and "prem" in r.text :
            price = r.json()["tradeMap"]["data"]["body"]["prem"]
            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新保险产品价格失败：%d*/"%dt["id"])

    def main(self):
        while True:
            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)
            if not dt:
                print("产品价格抓取完成~~~")
                return
            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)
            self.requestJson(dt)


if __name__ == '__main__':
    s = Spider()
    s.main()
